exports.init = init;

function init() {
  getPlayLists("initialize");
  actionBar("initialize");
}


/**
 * getPlayLists - builds the list of spotify playlists from reddit.com
 * input string caller - Handles initial page load vs refresh
 */
function getPlayLists(caller) {
    // Set variables/objects
    var url = "http://www.reddit.com/domain/spotify.com/.json?limit=150";
    var div = $("#mainDiv");
    var template = $("#arseTable").html();   
    var html =  Mustache.to_html(template, "");
    
    switch(caller) {
        // For initial page load just show the table headers
        case "initialize":
            div.html(html);
            stylize();  
            break;
        // Dims the currently loaded tbody while getting fresh data    
        case "refresh":
            div.find("tbody").addClass("ui-state-disabled");
            break;
    }

    $.ajaxSetup({
        'beforeSend': function(xhr) {xhr.setRequestHeader("User-FAIL", "ARSE_Request_Agent")}
    })

    // Get the JSON formated data
    $.getJSON(url, function (data) {
        // Grab only the spotify URI's
        $.each(data.data.children, function(index) {
            // Declare some variables
            var url = this.data.url;
            var info = url.split("/");
            var type = info[3];
            var uri = "";
            var ident = "";            
            var discard = false;
            
            if(!this.data.domain.match("^.*spotify\.com.*$")) {
                delete data.data.children[index];
            }
            // Some data manipulation
            date = new Date(this.data.created_utc*1000);
            data.data.children[index].data.date = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();// date.toDateString();
            
            var description = this.data.title;
            data.data.children[index].data.description = description.substring(0, 100);
            
            // Create a uniq identifier
            var uniq = Math.floor((Math.random()*100)+1);
            data.data.children[index].data.uniq = uniq;
            
            // Apply search filter if any 
            var search = $("#search_val").val();
            if(search.length) {
                if(!description.toLowerCase().match(search)) {
                    discard = true;
                    data.search = search;
                }
                
            }
            
            // Build the URI based on the type (album vs user playlist)
            switch(type) {
                case "user":
                    ident = info[5];
                    uri = "spotify:user:" + info[4] + ":playlist:" + info[6];
                    break;
                case "album":
                    uri = "spotify:album:" + info[4];
                    break;
                default:
                    discard = true;
            }

            // Discard anything not wanted 
            if(discard) {
                delete data.data.children[index];
            } else {
                data.data.children[index].data.uri = uri;
            }
            
        });

        // Create the templatized html
        html = Mustache.to_html(template, data);
        
        // Display the html
        div.html(html);

        // Stylize the table
        stylize();
          
        // Make the table sortable
        $("#tableData").tablesorter({
            sortList: [[5,1]]
        });
        
        // Throw in the refresh event handler
        $("#search").live("click", function() {
            getPlayLists("refresh");
            return false;
        });
        $("#search_val").live("keydown", function(event) {
            if (event.which == 13) {
                getPlayLists("refresh");
                event.preventDefault();
                return false;
            }
            return true;
        });
    });
};

/**
 * getThread - gets the comments for a given post
 * input obj elem - DOM element with data freighted in the attributes
 */
function getThread(elem) {
    // Grab some info to use later
    var src = elem.attr("href");
    var uniq = elem.attr("uniq");
    var row = elem.closest('tr');  
  
    // If there are already comments displayed, hide
    // and remove the element from the DOM
    if($("."+uniq).length) {
        $("."+uniq).hide("slow");
        $("."+uniq).remove();
        return;
    }
    
    // AJAX call and display specific variables
    var url = "http://www.reddit.com" + src + ".json";
    var template = $("#commentTable").html();
    var html = "";
    
    // Make the call
    $.getJSON(url, function(data) {
        // Only using the comments obj, not the parent that comes with it
        var comments = data[1]
        
        // Move some shit around for UI manipulation/display
        $.each(comments.data.children, function(index) {
            // Convert the timestamp to a human readable format
            var date = new Date(this.data.created_utc*1000);
            comments.data.children[index].data.date = date.toDateString();
            
            // Only use the first 150 characters of the comment, we don't
            // care about any more than that really.
            var description = this.data.body;
            comments.data.children[index].data.description = description.substring(0, 150);
            
            // Carry over the uniq identifier from the parent into the child
            comments.data.children[index].data.uniq = uniq;
            
        })
        // Format the JSON data using Mustache.js
        html = Mustache.to_html(template, comments);
        
        // Insert the html after this row
        row.after(html);

    });
    
    // Add some stylization
    stylize();
}

/**
 * actionBar - Builds the action bar for each row
 * input string state - Only being initialized for now
 */
function actionBar(state) {
    // Setup the Spotify API for music controls
    var sp = getSpotifyApi(1);
    var v = sp.require("sp://import/scripts/api/views");    
    
    // Verify state and continue
    if("initialize" == state) {
        tracks = new v.Player();
        $(".play").live("click", function() {
            // Reset the other play buttons in case they were used before
            $(".play").attr("src", "sp://arse/img/Play-Small.png");

            // Set this to the now playing button
            $(this).attr("src", "sp://arse/img/Playing-Small.png");
            
            // Play the relevant URI
            uri = $(this).attr("id");
            tracks.play(uri);
        });
        
        // Expand/collapse comments as appropriate
        $(".comments").live("click", function() {
            getThread($(this));
        });
    }
}

/**
 * stylize - stylizes various html elements
 */
function stylize() {
    var t = $("#tableData");
    t.find("tbody").removeClass("ui-state-disabled");
    t.addClass("ui-widget");
    t.css("width", "95%");
    t.css("border-collapse", "collapse");
    t.find("th").addClass("ui-widget-header");
    $(".posts").hover(
        function () {
            $(this).find("td").addClass("ui-state-hover");
        },
        function () {
            $(this).find("td").removeClass("ui-state-hover");
        }
    );
    t.find("tr.posts td").addClass("ui-widget-content");
}